package com.atguigu.myjuc.Pool;

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(),       // 核心线程数 = CPU核心数
                Runtime.getRuntime().availableProcessors() + 1,  // 最大线程数 = 核心数+1
                1L,                                             // 非核心线程空闲存活时间
                TimeUnit.SECONDS,                               // 时间单位（秒）
                new ArrayBlockingQueue<>(3),           // 任务队列（容量3）
                Executors.defaultThreadFactory()             // 默认线程工厂
                //new ThreadPoolExecutor.DiscardOldestPolicy()   // 拒绝策略：丢弃队列中最老的任务
        );
        try{
            for (int i = 1; i <=10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"为："+ i +"客户办理业务");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
    private static void defaultpool(){
        ExecutorService executorService = Executors.newFixedThreadPool(5);//一池固定线程数
        //ExecutorService executorService = Executors.newSingleThreadExecutor();//一池一线程
        //ExecutorService executorService = Executors.newCachedThreadPool();//一池多线程

        try {
            for (int i = 1; i <= 10; i++) {
                int finalI = i;
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"为："+ finalI+"客户办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //executorService.shutdown();//使用try catch关闭资源 （优雅关闭，等待已提交任务完成）
            executorService.shutdownNow();//如果需要立刻关闭使用 shutdownNow();
        }
    }
}
